import request from '../../utils/request'
var appInstance = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    productList: [],
    keyWord: null,
    totalPage: 1,
    pageNum: 1,
    show: false,
    checkProduct: null,
    retailPrice: null,
    wholesalePrice: null,
    scaPrice: null,
    isAdmin: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({ isAdmin: appInstance.globalData.isAdmin })
  },

  onSearch(event) {
    this.setData({
      keyWord: event.detail
    })
    this.getProductList()
  },
  setPrice(event) {
    let { checkProduct, retailPrice, wholesalePrice, scaPrice } = this.data
    const para = {
      id: checkProduct.id,
      retailPrice: parseInt(retailPrice, 10),
      wholesalePrice: parseInt(wholesalePrice, 10),
      scaPrice: parseInt(scaPrice, 10)
    }
    request('/smile/smileProduct/updatePrice', para, 'POST').then(() => {
      this.setData({ show: false })
      this.getProductList()
    })
  },
  handleInput(event) {},

  onClose() {
    this.setData({ show: false })
  },

  onClear() {
    this.setData({ keyWord: null })
    this.getProductList()
  },

  toEdit() {
    wx.navigateTo({
      url: '/pages/addProduct/addProduct'
    })
  },

  editPrice(event) {
    if (this.data.isAdmin) {
      let { productList } = this.data
      let checkProduct = productList.filter((item) => item.id == event.currentTarget.id)[0]
      this.setData({
        show: true,
        checkProduct,
        retailPrice: checkProduct.retailPrice,
        wholesalePrice: checkProduct.wholesalePrice,
        scaPrice: checkProduct.scaPrice
      })
    }
  },

  getProductList() {
    let { pageNum, keyWord } = this.data
    let para = {}
    if (keyWord != null) {
      para = {
        pageNum,
        keyWord
      }
    } else {
      para = {
        pageNum
      }
    }
    request('/smile/smileProduct/getAllList', para).then((res) => {
      res.list.map((item) => {
        item.image = item.image ? item.image + '?imageView2/2/w/600' : null
      })
      this.setData({
        productList: res.list
      })
    })
  },

  // 跳转到详情页
  toDetail(event) {
    let { id } = event.currentTarget
    wx.navigateTo({
      url: '/pages/productDetail/productDetail?id=' + id
    })
  },

  // 扫码
  handleScan() {
    let that = this
    wx.scanCode({
      success(res) {
        that.setData({ keyWord: res.result })
        that.getProductList()
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getTabBar().init()
    this.getProductList()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {}
})
